package main

import (
	"context"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/exporters/jaeger"
	"go.opentelemetry.io/otel/sdk/resource"
	"go.opentelemetry.io/otel/sdk/trace"
	semconv "go.opentelemetry.io/otel/semconv/v1.4.0"
	"time"
)

func main() {

	url := "http://127.0.0.1:14268/api/traces" //这个是jeager对应的地址
	exporter, err := jaeger.New(jaeger.WithCollectorEndpoint(jaeger.WithEndpoint(url)))
	if err != nil {
		panic(err)
	}

	provider := trace.NewTracerProvider(
		trace.WithBatcher(exporter),
		trace.WithBatcher(exporter),
		trace.WithResource(resource.NewWithAttributes(
			semconv.SchemaURL,
			//设置trace的名称，不设置默认显示文件名
			semconv.ServiceNameKey.String("mxshop-user"),
			//设置trace的属性，在tags里面显示
			attribute.String("environment", "dev"),
			attribute.Int("ID", 1),
		)),
	)
	otel.SetTracerProvider(provider)

	ctx, cancel := context.WithCancel(context.Background())
	defer func(ctx context.Context) {
		ctx, cancel = context.WithTimeout(ctx, time.Second*5)
		defer cancel()
		if provider.Shutdown(ctx); err != nil {
			panic(err)
		}
	}(ctx)

	tracer := otel.Tracer("mxshop-otel")
	_, span := tracer.Start(ctx, "func-main")
	//设置san的属性 在process里面显示
	var attrs []attribute.KeyValue
	attrs = append(attrs, attribute.String("key1", "value1"))
	span.SetAttributes(attrs...)
	//addEvent 会把信息添加到log中
	span.AddEvent("this is a event")
	time.Sleep(time.Second)
	span.End()
}
